package net.oschina.simpleplus.jwt;

import java.security.Key;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache.ValueWrapper;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;

import io.jsonwebtoken.CompressionCodecs;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.impl.crypto.MacProvider;
import net.oschina.simpleplus.vo.UserVo;

@Component
public class JwtFactory {

	private static final String JWT_USER_VO_CACHE = "jwtUserVoCache";

	@Autowired
	private CacheManager jwtCache;

	private Key key = MacProvider.generateKey();

	public String generateToken(UserVo userVo) {
		try {
			String token= Jwts.builder().setSubject(JSON.toJSONString(userVo)).compressWith(CompressionCodecs.GZIP)
					.setExpiration(new Date(System.currentTimeMillis() + TimeUnit.HOURS.toMillis(6)))
					.signWith(SignatureAlgorithm.HS512, key).compact();
			jwtCache.getCache(JWT_USER_VO_CACHE).put(userVo.getId(), userVo);
			return token;
		} catch (Exception e) {
			throw new RuntimeException("token error!");
		}
	}
	
	public UserVo getUserFromToken(String token){
		try {
			UserVo ret = JSON.parseObject(Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody().getSubject(), UserVo.class);
			ValueWrapper valw = jwtCache.getCache(JWT_USER_VO_CACHE).get(ret.getId());
			if(valw == null || valw.get() == null){
				throw new RuntimeException("expire");
			}
			if(!((UserVo) valw.get()).getTokenFlag().equals(ret.getTokenFlag())){
				throw new RuntimeException("expire");
			}
			return ret;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

}
